package com.xcw.bos.shiro;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.xcw.bos.dao.IFunctionDao;
import com.xcw.bos.dao.IUserDao;
import com.xcw.bos.domain.Function;
import com.xcw.bos.domain.User;
import com.xcw.bos.service.IUserService;

public class BOSRealm extends AuthorizingRealm {
    @Resource
    private IUserDao userDao;
    @Resource
    private IUserService userService;
    @Resource
    private IFunctionDao functionDao;
    //授权方法
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//获取当前登录用户
		User user = (User) principals.getPrimaryPrincipal();
		if(user.getUsername().equals("admin")){
			//超级管理员,赋给所有权限
			List<Function> list = functionDao.findAll();
			for(Function function : list){
				info.addStringPermission(function.getCode());
			}
		}else{
			//普通用户
			List<Function> list = functionDao.findFunctionListByUserId(user.getId());
			for(Function function : list){
				String code = function.getCode();//权限关键字
				info.addStringPermission(code);//授权
			}
		}
	
		return info;
	}
    //认证方法
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		System.out.println("realm中认证方法执行了");
		UsernamePasswordToken uptoken = (UsernamePasswordToken)token;
		String username = uptoken.getUsername();
		char[] password = uptoken.getPassword();
		System.out.println(username);
		
		//根据当前用户名查询数据库中的密码，由shiro框架负责比对
		User user = userDao.findUserByUsername(username);
		if(user == null){
			return null;
		}
		String dbpwd = user.getPassword();
		AuthenticationInfo info = new SimpleAuthenticationInfo(user, dbpwd, this.getName());
		return info;//如果返回null，框架认为账户不存在
	}
	
}
